package org.jeecgframework.web.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.DataUtils;
import org.jeecgframework.core.util.DateUtils;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.service.ZyTimeTaskForWarrantyPeriodSevice;
import org.jeecgframework.web.system.pojo.base.ZyFileLogEntity;
import org.jeecgframework.web.system.pojo.base.ZyWarrantyPeriodCEntity;
import org.jeecgframework.web.system.pojo.base.ZyWarrantyPeriodEntity;
import org.jeecgframework.web.system.pojo.base.ZyWarrantyPeriodHEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.ExcelUtil;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("zyTimeTaskForWarrantyPeriodService")
@Transactional
public class ZyTimeTaskForWarrantyPeriodServiceImpl extends CommonServiceImpl implements ZyTimeTaskForWarrantyPeriodSevice {

	@Autowired
	private SystemService systemService;

	/**
	 * @Description 解析EXCEL
	 * @param HttpServletRequest
	 *            通过前台请求获得文件流
	 */
	public void zyRecordImport() {

		StringBuilder sql = null;

		System.out.println("定时任务开始 - 导入保期数据" + DataUtils.getDate("hh:mm:ss.SSS"));

		// 根据业务类型和状态查询文件管理
		ZyFileLogEntity fileLog = this.getPath(StaticValue.IMPORT_FILE_PERIOD_RECORDER, StaticValue.DIC_TRUE_OR_FALSE_NUM_0);

		try {

			if (StringUtil.isNotEmpty(fileLog)) {
				// 文件管理不为空

				// 根据文件路径解析Excel
				List<Map<String, Object>> dataList = ExcelUtil.analyzeExcel(fileLog.getFilePath(), StaticValue.DIC_TRUE_OR_FALSE_NUM_1);

				// 查询全部保期记录
				List<ZyWarrantyPeriodEntity> oldZyWarrantyPeriodAll = systemService.getList(ZyWarrantyPeriodEntity.class);

				// 新增的全部保期记录
				List<ZyWarrantyPeriodEntity> newZyWarrantyPeriodAll = new ArrayList<ZyWarrantyPeriodEntity>();

				sql = new StringBuilder("select max(t.version) version from zy_warranty_period_h t");

				// 根据SQL获取版本
				String version = this.getVersion(sql.toString());

				ZyWarrantyPeriodEntity zwpe = null;
				// 遍历保期记录
				for (int i = 1; i < dataList.size(); i++) {

					// 实例化一个保期记录
					zwpe = new ZyWarrantyPeriodEntity();

					zwpe.setItem(StringUtil.getString(dataList.get(i).get(StaticValue.DIC_TRUE_OR_FALSE_NUM_0)));
					zwpe.setSn(StringUtil.getString(dataList.get(i).get(StaticValue.DIC_TRUE_OR_FALSE_NUM_1)));
					zwpe.setItemDesc(StringUtil.getString(dataList.get(i).get("2")));
					zwpe.setAlternateSerialNr(StringUtil.getString(dataList.get(i).get("3")));
					zwpe.setCreationDate(DateUtils.str2Date(StringUtil.getString(dataList.get(i).get("4")), DateUtils.sdf_date_1));
					zwpe.setSerializedItemGroup(StringUtil.getString(dataList.get(i).get("5")));
					zwpe.setSoldToBp(StringUtil.getString(dataList.get(i).get("6")));
					zwpe.setSoldToBpDesc(StringUtil.getString(dataList.get(i).get("7")));
					zwpe.setSoldToAddress(StringUtil.getString(dataList.get(i).get("8")));
					zwpe.setSoldToAddrCountry(StringUtil.getString(dataList.get(i).get("9")));
					zwpe.setSoldToContact(StringUtil.getString(dataList.get(i).get("10")));
					zwpe.setWarranty(StringUtil.getString(dataList.get(i).get("11")));
					zwpe.setInstallationDate(DateUtils.str2Date(StringUtil.getString(dataList.get(i).get("12")), DateUtils.sdf_date_1));
					zwpe.setRevision(StringUtil.getString(dataList.get(i).get("13")));
					zwpe.setDeliveryDate(DateUtils.str2Date(StringUtil.getString(dataList.get(i).get("14")), DateUtils.sdf_date_1));
					zwpe.setSalesOrder(StringUtil.getString(dataList.get(i).get("15")));
					zwpe.setSalesOrderLine(StringUtil.getString(dataList.get(i).get("16")));
					zwpe.setCluster(StringUtil.getString(dataList.get(i).get("17")));
					zwpe.setClusterDesc(StringUtil.getString(dataList.get(i).get("18")));
					zwpe.setTopItem(StringUtil.getString(dataList.get(i).get("19")));
					zwpe.setTopSerialNr(StringUtil.getString(dataList.get(i).get("20")));
					zwpe.setWorkSiteAddress(StringUtil.getString(dataList.get(i).get("21")));
					zwpe.setLot(StringUtil.getString(dataList.get(i).get("22")));
					zwpe.setSlsComp(StringUtil.getString(dataList.get(i).get("23")));
					zwpe.setSlsSoldToBp(StringUtil.getString(dataList.get(i).get("24")));
					zwpe.setSlsSoldToBpDesc(StringUtil.getString(dataList.get(i).get("25")));
					zwpe.setSlsShipToCountry(StringUtil.getString(dataList.get(i).get("26")));
					zwpe.setLob(StringUtil.getString(dataList.get(i).get("27")));
					zwpe.setEndOfWarranty(DateUtils.str2Date(StringUtil.getString(dataList.get(i).get("28")), DateUtils.sdf_date_1));
					zwpe.setServiceContract(StringUtil.getString(dataList.get(i).get("29")));
					zwpe.setServiceContractDesc(StringUtil.getString(dataList.get(i).get("30")));
					zwpe.setStartContractCoverage(DateUtils.str2Date(StringUtil.getString(dataList.get(i).get("31")), DateUtils.sdf_date_1));
					zwpe.setEndContractCoverage(DateUtils.str2Date(StringUtil.getString(dataList.get(i).get("32")), DateUtils.sdf_date_1));
					zwpe.setVersion(version);
					// 将保期记录保存到集合当中
					newZyWarrantyPeriodAll.add(zwpe);

				}

				// 添加保期记录集合
				systemService.batchSave(newZyWarrantyPeriodAll);

				if (oldZyWarrantyPeriodAll != null && oldZyWarrantyPeriodAll.size() > 0) {
					// 保期记录集合不等于空并且长度大于0

					this.compare(oldZyWarrantyPeriodAll, newZyWarrantyPeriodAll);

				}

				/** -------------复制 对象--------begin--------- */

				sql = new StringBuilder("select max(t.version) version from zy_warranty_period_h t");

				// 获取版本信息
				version = this.getVersion(sql.toString());

				// 保期记录历史集合
				List<ZyWarrantyPeriodHEntity> zyWarrantyPeriodHList = new ArrayList<ZyWarrantyPeriodHEntity>();

				// 保期记录历史
				ZyWarrantyPeriodHEntity zyWarrantyPeriodH = null;

				// 遍历
				for (ZyWarrantyPeriodEntity zyWarrantyPeriod : newZyWarrantyPeriodAll) {

					// 实例化保期记录历史
					zyWarrantyPeriodH = new ZyWarrantyPeriodHEntity();

					// 复制数据
					BeanUtils.copyProperties(zyWarrantyPeriodH, zyWarrantyPeriod);

					// 添加版本
					zyWarrantyPeriodH.setVersion(version);

					// 添加到保期记录历史集合当中
					zyWarrantyPeriodHList.add(zyWarrantyPeriodH);

				}

				// 保存新保期记录历史集合的数据
				systemService.batchSave(zyWarrantyPeriodHList);

				/** --------------复制 对象--------end----- */

				// 删除历史数据
				systemService.deleteAllEntitie(oldZyWarrantyPeriodAll);

				// 根据文件记录ID查询出文件记录
				ZyFileLogEntity zyfileLog = systemService.get(ZyFileLogEntity.class, fileLog.getId());

				// 更改状态
				zyfileLog.setStatus(StaticValue.DIC_TRUE_OR_FALSE_NUM_1);

				// 保存
				systemService.saveOrUpdate(zyfileLog);

				System.out.println("-----------------task end-----------");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title：compare
	 * @Description：最新一次导入和上一次导放进行对比,如果根据需要比较的字段发现有变化的则保存到差异表中
	 * @author：LeiYoung
	 * @Date：2016年10月10日 下午3:57:09
	 * @param oldZyWarrantyPeriodAll
	 *            上一次导入记录
	 * @param newZyWarrantyPeriodAll
	 *            本次导入记录
	 */
	private void compare(List<ZyWarrantyPeriodEntity> oldZyWarrantyPeriodAll, List<ZyWarrantyPeriodEntity> newZyWarrantyPeriodAll) {

		boolean save = true;

		// 保期记录对比集合
		List<ZyWarrantyPeriodCEntity> zyWarrantyPeriodCEntityList = new ArrayList<ZyWarrantyPeriodCEntity>();

		// 保期记录对比[新]
		ZyWarrantyPeriodCEntity zwpceNew = null;

		// 保期记录对比[旧]
		ZyWarrantyPeriodCEntity zwpceOld = null;

		// 新数据SN集合
		List<String> newSnList = new ArrayList<String>();

		try {

			// 遍历新导入的保期记录
			for (ZyWarrantyPeriodEntity zyWarrantyPeriodNew : newZyWarrantyPeriodAll) {

				// for 中不能存在break || return

				// 将新数据的SN添加到集合当中
				newSnList.add(zyWarrantyPeriodNew.getSn());

				// 是否新增
				save = true;

				// 遍历历史保期记录
				for (ZyWarrantyPeriodEntity zyWarrantyPeriodOld : oldZyWarrantyPeriodAll) {

					if (zyWarrantyPeriodNew.getSn().equals(zyWarrantyPeriodOld.getSn())) {
						// 新的保期记录数据中的SN等于老数据记录中的SN

						// 更改新状态为不新增
						save = false;

						// 合同开始日_日期转换为字符串
						String startContractCoverage = DataUtils.date2Str(zyWarrantyPeriodNew.getStartContractCoverage(), DateUtils.sdf_date_1);

						// 合同结束日_日期转换为字符串
						String endContractCoverage = DataUtils.date2Str(zyWarrantyPeriodNew.getEndContractCoverage(), DateUtils.sdf_date_1);

						// 合同开始日和合同结束日 不等于 "1899-12-30 00:00:00"
						boolean booContractCoverage = !"1899-12-30 00:00:00".equals(startContractCoverage) && !"1899-12-30 00:00:00".equals(endContractCoverage);

						// 合同开始日不等于空并且新数据合同开始日不等于老数据合同开始日
						boolean booCluster = zyWarrantyPeriodNew.getCluster() != null && !zyWarrantyPeriodNew.getCluster().equals(zyWarrantyPeriodOld.getCluster());

						// 保修截止日不等于空并且新数据保修截止日不等于老数据保修截止日
						boolean booEndOfWarranty = zyWarrantyPeriodNew.getEndOfWarranty() != null && !zyWarrantyPeriodNew.getEndOfWarranty().equals(zyWarrantyPeriodOld.getEndOfWarranty());

						// 服务合同不等于空并且新数据服务合同不等于老数据服务合同
						boolean booServiceContract = zyWarrantyPeriodNew.getServiceContract() != null && !zyWarrantyPeriodNew.getServiceContract().equals(zyWarrantyPeriodOld.getServiceContract());

						// 合同开始日不等于空并且新数据合同开始日不等于老数据合同开始日
						boolean booStartContractCoverage = zyWarrantyPeriodNew.getStartContractCoverage() != null
								&& !zyWarrantyPeriodNew.getStartContractCoverage().equals(zyWarrantyPeriodOld.getStartContractCoverage());

						// 合同结束日不等于空并且新数据合同结束日不等于老数据合同结束日
						boolean booEndContractCoverage = zyWarrantyPeriodNew.getEndContractCoverage() != null
								&& !zyWarrantyPeriodNew.getEndContractCoverage().equals(zyWarrantyPeriodOld.getEndContractCoverage());

						if (booContractCoverage) {

							if (booCluster || booEndOfWarranty || booServiceContract || booStartContractCoverage || booEndContractCoverage) {

								zwpceNew = new ZyWarrantyPeriodCEntity();
								zwpceOld = new ZyWarrantyPeriodCEntity();

								zwpceNew.setSn(zyWarrantyPeriodNew.getSn());
								zwpceOld.setSn(zyWarrantyPeriodOld.getSn());

								zwpceNew.setCluster(zyWarrantyPeriodNew.getCluster());
								zwpceOld.setCluster(zyWarrantyPeriodOld.getCluster());

								zwpceNew.setEndOfWarranty(zyWarrantyPeriodNew.getEndOfWarranty());
								zwpceOld.setEndOfWarranty(zyWarrantyPeriodOld.getEndOfWarranty());

								zwpceNew.setServiceContract(zyWarrantyPeriodNew.getServiceContract());
								zwpceOld.setServiceContract(zyWarrantyPeriodOld.getServiceContract());

								zwpceNew.setStartContractCoverage(zyWarrantyPeriodNew.getStartContractCoverage());
								zwpceOld.setStartContractCoverage(zyWarrantyPeriodOld.getStartContractCoverage());

								zwpceNew.setEndContractCoverage(zyWarrantyPeriodNew.getEndContractCoverage());
								zwpceOld.setEndContractCoverage(zyWarrantyPeriodOld.getEndContractCoverage());

								zwpceNew.setType(StaticValue.DIC_FILE_UPDATE);
								zwpceOld.setType(StaticValue.DIC_FILE_UPDATE);

								if (booCluster) {
									zwpceNew.setClusterColour("red");
								}
								if (booEndOfWarranty) {
									zwpceNew.setEndOfWarrantyrColour("red");
								}
								if (booServiceContract) {
									zwpceNew.setServiceContractColour("red");
								}
								if (booStartContractCoverage) {
									zwpceNew.setStartContractCoverageColour("red");
								}
								if (booEndContractCoverage) {
									zwpceNew.setEndContractCoverageColour("red");
								}

								zwpceNew.setStatus(StaticValue.DIC_TRUE_OR_FALSE_NUM_0);
								zwpceOld.setStatus(StaticValue.DIC_TRUE_OR_FALSE_NUM_0);

								zwpceNew.setImportDate(new Date());
								zwpceOld.setImportDate(new Date());

								zwpceNew.setVersion(zyWarrantyPeriodNew.getVersion());
								zwpceOld.setVersion(zyWarrantyPeriodOld.getVersion());

								zyWarrantyPeriodCEntityList.add(zwpceNew);
								zyWarrantyPeriodCEntityList.add(zwpceOld);

							}

						}

					}

				}
				// 新增
				if (save) {

					zwpceNew = new ZyWarrantyPeriodCEntity();
					zwpceNew.setSn(zyWarrantyPeriodNew.getSn());
					zwpceNew.setCluster(zyWarrantyPeriodNew.getCluster());
					zwpceNew.setEndOfWarranty(zyWarrantyPeriodNew.getEndOfWarranty());
					zwpceNew.setServiceContract(zyWarrantyPeriodNew.getServiceContract());
					zwpceNew.setStartContractCoverage(zyWarrantyPeriodNew.getStartContractCoverage());
					zwpceNew.setEndContractCoverage(zyWarrantyPeriodNew.getEndContractCoverage());
					zwpceNew.setType(StaticValue.DIC_FILE_CREATE);
					zwpceNew.setStatus(StaticValue.DIC_TRUE_OR_FALSE_NUM_0);
					zwpceNew.setVersion(zyWarrantyPeriodNew.getVersion());
					zwpceNew.setImportDate(new Date());

					zyWarrantyPeriodCEntityList.add(zwpceNew);

				}
			}

			// 遍历就数据
			for (ZyWarrantyPeriodEntity zyWarrantyPeriodOld : oldZyWarrantyPeriodAll) {

				if (!newSnList.contains(zyWarrantyPeriodOld.getSn())) {
					// 老数据的SN在新数据中找不到

					zwpceOld = new ZyWarrantyPeriodCEntity();
					zwpceOld.setSn(zyWarrantyPeriodOld.getSn());
					zwpceOld.setCluster(zyWarrantyPeriodOld.getCluster());
					zwpceOld.setEndOfWarranty(zyWarrantyPeriodOld.getEndOfWarranty());
					zwpceOld.setServiceContract(zyWarrantyPeriodOld.getServiceContract());
					zwpceOld.setStartContractCoverage(zyWarrantyPeriodOld.getStartContractCoverage());
					zwpceOld.setEndContractCoverage(zyWarrantyPeriodOld.getEndContractCoverage());
					zwpceOld.setType(StaticValue.DIC_FILE_DELETE);
					zwpceOld.setStatus(StaticValue.DIC_TRUE_OR_FALSE_NUM_0);
					zwpceOld.setVersion(zyWarrantyPeriodOld.getVersion());
					zwpceOld.setImportDate(new Date());

					zyWarrantyPeriodCEntityList.add(zwpceOld);

				}

			}

			systemService.batchSave(zyWarrantyPeriodCEntityList);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @Title：getPath
	 * @Description：获得文件路径
	 * @author：LeiYoung
	 * @Date：2016年10月10日 下午3:39:24
	 * @param businessType
	 *            业务类型
	 * @param status
	 *            状态
	 * @return ZyFileLogEntity
	 */
	private ZyFileLogEntity getPath(String businessType, String status) {

		// 根据业务类型和状态查询
		List<ZyFileLogEntity> fileLogList = systemService.findHql("from ZyFileLogEntity where businessType = ? and status = ? order by createDate desc", businessType, status);

		if (fileLogList != null && fileLogList.size() > 0) {
			// 非空判断

			return fileLogList.get(0);

		}
		return null;
	}

	/**
	 * @Title：getVersion
	 * @Description：获得最新版本号
	 * @author：LeiYoung
	 * @Date：2016年10月10日 下午4:43:05
	 * @param sql
	 * @return String
	 */
	private String getVersion(String sql) {
		String version = "V1.0";
		Map<String, Object> filePathMap = systemService.findOneForJdbc(sql.toString());
		if (filePathMap != null) {
			if (StringUtil.isNotEmpty(filePathMap.get("version"))) {
				String ver = filePathMap.get("version").toString().substring(1);
				float temp = Float.valueOf(ver);
				version = "V" + (temp + 1);
			}
		}
		return version;
	}
}
